import { ElMessage } from "element-plus";
import router from "./router";
import { useUserStore } from "./stores/user";
import { getProfileAPI } from "./apis/user";
import type { RouteRecordRaw } from "vue-router";
import { asyncRoutes } from "./router/asyncRouter";

// 路由白名单
const WHITE_LIST = ["/login", "/404"];

// 获取一级路由权限
const getFirstRouterPerms = (Permissions: string[]) => {
  const  tempArr = Permissions.map((item) => item.split(':')[0])
  return Array.from(new Set(tempArr))
}

// 获取二级路由权限
const getSecondRouterPerms = (Permissions: string[]) => {
  const tempArr = Permissions.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return Array.from(new Set(tempArr))
}

const getRoutes = (
  firstRouterPerms: string[],
  SecondRouterPerms: string[],
  asyncRoutes: RouteRecordRaw[]
) => {
  console.log(firstRouterPerms, SecondRouterPerms, asyncRoutes)
  // 过滤出一级路由
  const firstRoutes = asyncRoutes.filter(route => {
    return firstRouterPerms.includes(route.meta!.permission!)
  })
  // console.log('筛选后的一级路由',firstRoutes)
}


// 路由导航守卫
router.beforeEach(async (to, from, next) => {
  const store = useUserStore()
  // 判断是否有 token
  if (store.token) {
    // 有 token，放行
    next()
    const store = useUserStore()
    if (!store.profile.id) {
      const res = await getProfileAPI()
      store.setProfile(res.data)
      const firstRouterPerms = getFirstRouterPerms(res.data.permissions)
      // console.log('✅一级路由路由信息', firstRouterPerms)
      const SecondRouterPerms = getSecondRouterPerms(res.data.permissions)
      // console.log('✅一级路由路由信息', SecondRouterPerms)
      getRoutes(firstRouterPerms,SecondRouterPerms,asyncRoutes)
    }
  } else {
    // 是否在白名单中
    if (WHITE_LIST.includes(to.path)) {
      // 在白名单中，放行
      next()
    } else {
      // 不在白名单中，跳转到登录页
      next('/login')
      ElMessage.warning('登录信息无效，请先登录')
    }
  }
})